package com.github.leecho.ssc.controller;

import com.github.leecho.ssc.captcha.CaptchaImage;
import com.github.leecho.ssc.captcha.DefaultCaptchaImage;
import com.github.leecho.ssc.captcha.RandomCaptcha;
import com.github.leecho.ssc.captcha.repository.CaptchaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author LIQIU
 * created on 2020/11/13
 **/
@Controller
public class CaptchaController {

    private final CaptchaRepository<HttpServletRequest> captchaRepository;

    @Autowired
    public CaptchaController(CaptchaRepository<HttpServletRequest> captchaRepository) {
        this.captchaRepository = captchaRepository;
    }

    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        RandomCaptcha randomCaptcha = new RandomCaptcha(4);
        captchaRepository.save(request, randomCaptcha.getValue());
        CaptchaImage captchaImage = new DefaultCaptchaImage(200, 60, randomCaptcha.getValue());
        captchaImage.write(response.getOutputStream());
    }
}
